import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../../fluttercommon.dart';

typedef bool WebUrlInterceptor(BuildContext context, String url);

class WebPage extends StatefulWidget {
  final String url;
  final String? titleText;
  final WebUrlInterceptor? interceptor;
  final Set<JavascriptChannel>? javascriptChannels;

  const WebPage({
    Key? key,
    required this.url,
    this.titleText,
    this.interceptor,
    this.javascriptChannels,
  }) : super(key: key);

  @override
  WebPageState createState() => WebPageState();
}

class WebPageState extends State<WebPage> {
  late WebViewController webViewController;
  ValueNotifier<bool> _showIndicator = ValueNotifier(true);

  bool get hasAppBar => widget.titleText?.isNotEmpty ?? false;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (await webViewController.canGoBack()) {
          webViewController.goBack();
          return false;
        }
        return true;
      },
      child: Scaffold(
        appBar: hasAppBar
            ? AppBar(
                title: Text(this.widget.titleText ?? ""),
                centerTitle: true,
              )
            : null,
        body: Stack(
          children: <Widget>[
            Container(color: Colors.white),
            WebView(
              initialUrl: widget.url,
              javascriptMode: JavascriptMode.unrestricted,
              javascriptChannels: widget.javascriptChannels,
              onPageFinished: (u) {
                _showIndicator.value = false;
              },
              onWebViewCreated: (controller) {
                controller.clearCache();
                webViewController = controller;
              },
              navigationDelegate:
                  widget.interceptor != null ? _navigationDelegate : null,
            ),
            ValueListenableBuilder<bool>(
              valueListenable: _showIndicator,
              builder: (BuildContext context, bool value, Widget? child) {
                return value == true
                    ? Container(
                        color: Colors.white,
                        child: Center(
                          child: CupertinoActivityIndicator(),
                        ),
                      )
                    : Offstage();
              },
            ),
          ],
        ),
      ),
    );
  }

  NavigationDecision _navigationDelegate(NavigationRequest request) {
    if (widget.interceptor!(context, request.url) == true) {
      return NavigationDecision.prevent;
    } else {
      return NavigationDecision.navigate;
    }
  }
}
